package com.cskaoyan.service.impl;

import com.cskaoyan.bean.advert.AdvertAddVo;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.po.MarketAd;
import com.cskaoyan.bean.po.MarketAdExample;
import com.cskaoyan.bean.advert.AdvertInfoVo;
import com.cskaoyan.mapper.MarketAdMapper;
import com.cskaoyan.service.AdvertService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author LiangRuiJiang
 * @since 2022/06/05  14:52
 */
@Service
public class AdvertServiceImpl implements AdvertService {

    @Autowired
    MarketAdMapper marketAdMapper;


    @Override
    public AdvertInfoVo queryAdvert(BaseParam param, String name, String content) {
        PageHelper.startPage(param.getPage(), param.getLimit());

        MarketAdExample example = new MarketAdExample();
        MarketAdExample.Criteria criteria = example.createCriteria();
        String nameParm = null;
        String contentParm = null;
        if (name == null && content == null) {
            //如果为null，则全部查询
            nameParm = "%%";
            contentParm = "%%";
        } else {
            nameParm = "%" + name + "%";
            contentParm = "%" + content + "%";
        }
        example.setOrderByClause(param.getSort() + " " +param.getOrder());
        criteria.andNameLike(nameParm);
        criteria.andContentLike(contentParm);
        criteria.andDeletedEqualTo(false);
        List<MarketAd> marketAds = marketAdMapper.selectByExample(example);

        PageInfo pageInfo = new PageInfo(marketAds);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return new AdvertInfoVo(total, pages, param.getLimit(), param.getPage(), marketAds);
    }

    @Override
    @Transactional
    public AdvertAddVo createAdvert(MarketAd marketAd) {
        marketAd.setAddTime(new Date());
        marketAd.setUpdateTime(new Date());
        marketAdMapper.insertReturnPrimarykey(marketAd);

        // new AdvertAddVo()
        return new AdvertAddVo(marketAd.getId(),marketAd.getAddTime(),marketAd.getName(),marketAd.getUpdateTime(),marketAd.getPosition(),marketAd.getUrl(),marketAd.getContent(),marketAd.getEnabled());
    }

    @Override
    @Transactional
    public MarketAd updateAdvert(MarketAd marketAd) {
        marketAd.setUpdateTime(new Date());
        MarketAdExample example = new MarketAdExample();
        MarketAdExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(marketAd.getId());
        marketAd.setDeleted(true);

        marketAdMapper.updateByExampleSelective(marketAd,example);
        MarketAd marketAdNew = marketAdMapper.selectByPrimaryKey(marketAd.getId());
        return marketAdNew;
    }


}
